package com.taoym.voucher.common.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taoym.voucher.common.constant.MessageTemplateConstant;
import com.taoym.voucher.common.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @coder taoym
 * @datetime 2021/7/17 17:39
 * @desc 小程序消息服务
 */
@Slf4j
public class XcxMessageService {

    /**
     * @coder taoym
     * @datetime 2021/7/17 17:42
     * @desc 小程序发送消息
     */
    public static Boolean sendXcxMessage(String openId, String accessToken, Map<String, Object> dataMap) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("touser", openId);
        param.put("template_id", MessageTemplateConstant.CASH_MESSAGE_TEMPLATE_ID);
        param.put("page", "pages/index/index");
        param.put("data", dataMap);
        param.put("miniprogram_state", "trial");
        param.put("lang", "zh_CN");

        log.info("发送消息 {}", JSON.toJSONString(param));
        String response = HttpClientUtils.doPost(url, JSON.toJSONString(param));
        log.info("返回值 {}", response);

        JSONObject messageResp = JSON.parseObject(response);

        if (messageResp.get("errcode").equals(0)) {
            return true;
        } else {
            return false;
        }
    }
}
